package com.buybuyyi.stylistcrm.order.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.buybuyyi.stylistcrm.order.dao.ConsigneeDao;
import com.buybuyyi.stylistcrm.order.dao.PurchaseOrderDao;
import com.buybuyyi.stylistcrm.order.dao.PurchaseOrderGoodsDao;
import com.buybuyyi.stylistcrm.order.helper.ConsigneeHelper;
import com.buybuyyi.stylistcrm.order.helper.OrderGoodsHelper;
import com.buybuyyi.stylistcrm.order.po.Consignee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.buybuyyi.stylistcrm.consts.DateFormatPattern;
import com.buybuyyi.stylistcrm.order.po.PurchaseOrder;
import com.buybuyyi.stylistcrm.order.po.PurchaseOrderGoods;
import com.buybuyyi.stylistcrm.utils.DateUtil;
import stylistcrm.core.query.ResultPagerModel;
import stylistcrm.core.services.order.dto.OrderGoodsDto;
import stylistcrm.core.services.order.dto.PurchaseOrderDto;
import stylistcrm.core.services.order.dto.QueryOrderConditionDto;
import stylistcrm.core.services.order.enums.EnumExceptionCode;
import stylistcrm.core.services.order.exception.BizException;
import stylistcrm.core.services.order.service.PurchaseOrderService;

/**
 * Created by cheny on 2016/8/25.
 */
@Service
public class PurchaseOrderServiceImpl implements PurchaseOrderService {

    @Autowired
    private PurchaseOrderDao purchaseOrderDao;
    
    @Autowired
    private PurchaseOrderGoodsDao purchaseOrderGoodsDao;

	@Autowired
	private ConsigneeDao consigneeDao;

    /**
     * 创建进货单
     * @param purchaseOrder
     * @return
     * @throws BizException 
     */
    @Override
    public Boolean createPurchaseOrder(PurchaseOrderDto purchaseOrder) throws BizException {
		//校验参数不为空
    	if(null == purchaseOrder){
    		throw new BizException(EnumExceptionCode.EC0001);
    	}
		//校验收货地址不为空
		Consignee consignee=ConsigneeHelper.getOrderConsignee(purchaseOrder);
		if(null==consignee){
			throw new BizException(EnumExceptionCode.EC0002);
		}
		if(consignee.getId()!=null){
			//若收货地址存在更新收货地址
			consigneeDao.updateByPrimaryKeySelective(consignee);
		}else{
			//不存在新增收货地址
			Integer consigneeId=consigneeDao.insertSelective(consignee);
			purchaseOrder.setConsigneeId(consigneeId);
		}
		//将商品信息字符串转换为对象
		OrderGoodsHelper.setGoodsList(purchaseOrder);
		PurchaseOrder order=convertDto2Entity(purchaseOrder);
    	if(null!=order){
			//保存进货单信息
    		Integer ret=purchaseOrderDao.insertSelective(order);
        	if(ret<=0){
        		throw new BizException(EnumExceptionCode.EC0008);
        	}
			//获取商品信息
			List<OrderGoodsDto> goodsList=purchaseOrder.getGoods();
			if(null==goodsList||goodsList.isEmpty()){
				throw new BizException(EnumExceptionCode.EC0009);
			}
			for(OrderGoodsDto goods:goodsList){
				PurchaseOrderGoods orderGoods=convertDto2Entity(goods);
				if(null==orderGoods){
					continue;
				}
				orderGoods.setPurchaseOrderId(order.getId());
				//保存商品信息
				purchaseOrderGoodsDao.insertSelective(orderGoods);
			}
    	}
        return Boolean.TRUE;
    }
    /**
     * 
     * @描述：将进货单dto转换为entity
     * @param purchaseOrderDto
     * @return
     * @return PurchaseOrder
     * @exception
     * @createTime：2016年8月31日
     * @author: chenyong
     */
    private PurchaseOrder convertDto2Entity(PurchaseOrderDto purchaseOrderDto){
    	if(null == purchaseOrderDto){
    		return null;
    	}
    	PurchaseOrder order=new PurchaseOrder();
    	order.setStylistId(purchaseOrderDto.getStylistId());
    	order.setBelongToId(purchaseOrderDto.getBelongToId());
    	order.setConsigneeId(purchaseOrderDto.getConsigneeId());
    	order.setAuditStatus(purchaseOrderDto.getAuditStatus());
    	order.setDescription(purchaseOrderDto.getDescription());
    	order.setModifierId(purchaseOrderDto.getModifierId());
    	if(null!=purchaseOrderDto.getModifyTime()){
    		order.setModifyTime(DateUtil.parseDate(purchaseOrderDto.getModifyTime(), DateFormatPattern.PATTERN_YYYY_MM_DD_HHMMSS));
    	}
    	order.setOrderStatus(purchaseOrderDto.getOrderStatus());
    	if(null!=purchaseOrderDto.getOrderTime()){
    		order.setOrderTime(DateUtil.parseDate(purchaseOrderDto.getOrderTime(),DateFormatPattern.PATTERN_YYYY_MM_DD_HHMMSS));
    	}else{
    		order.setOrderTime(new Date());
    	}
    	order.setPayStatus(purchaseOrderDto.getPayStatus());
    	if(null!=purchaseOrderDto.getPayTime()){
    		order.setPayTime(DateUtil.parseDate(purchaseOrderDto.getPayTime(),DateFormatPattern.PATTERN_YYYY_MM_DD_HHMMSS));
    	}
    	order.setPayWay(purchaseOrderDto.getPayWay());
    	order.setTotalPrice(purchaseOrderDto.getTotalPrice());
    	return order;
    }
    /**
     * 
     * @描述：将进货单商品dto转换为entity
     * @param goodsDto
     * @return
     * @return PurchaseOrderGoods
     * @exception
     * @createTime：2016年8月31日
     * @author: chenyong
     */
    private PurchaseOrderGoods convertDto2Entity(OrderGoodsDto goodsDto){
    	if(null==goodsDto){
    		return null;
    	}
    	PurchaseOrderGoods orderGoods=new PurchaseOrderGoods();
    	orderGoods.setColor(goodsDto.getColor());
    	orderGoods.setCount(goodsDto.getCount());
    	orderGoods.setCreateTime(new Date());
    	orderGoods.setDeliveredCount(goodsDto.getDeliveredCount());
    	orderGoods.setDesignerId(goodsDto.getDesignerId());
    	orderGoods.setGoodsBuyingPrice(goodsDto.getGoodsBuyingPrice());
    	orderGoods.setGoodsId(goodsDto.getGoodsId());
    	orderGoods.setGoodsName(goodsDto.getGoodsName());
    	orderGoods.setGoodsSalePrice(goodsDto.getGoodsSalePrice());
    	orderGoods.setGoodsTagPrice(goodsDto.getGoodsTagPrice());
    	orderGoods.setOrderPrice(goodsDto.getOrderPrice());
    	orderGoods.setSize(goodsDto.getSize());
    	orderGoods.setTotalPrice(goodsDto.getTotalPrice());
    	orderGoods.setYardageId(goodsDto.getYardageId());
    	return orderGoods;
    }
    /**
     * 进货单分页查询
     */
	@Override
	public ResultPagerModel<PurchaseOrderDto> getPageList(QueryOrderConditionDto queryCondition) {
		Integer currentPage=queryCondition.getCurrentPage();
		Integer pageSize=queryCondition.getPageSize();
		if(currentPage==null){
			currentPage=1;
			queryCondition.setCurrentPage(currentPage);
		}
		if(pageSize==null){
			pageSize=15;
			queryCondition.setPageSize(pageSize);
		}
		queryCondition.setStart((currentPage-1)*pageSize);
		//根据查询条件查询主键（由于商品名称存在多表中，按商品名称查询订单先查订单主键）
		List<Integer> ids=this.getPageIdList(queryCondition);
		ResultPagerModel<PurchaseOrderDto> resultPager=new ResultPagerModel<PurchaseOrderDto>();
		resultPager.setCurrentPage(currentPage);
		resultPager.setPageSize(pageSize);
		List<PurchaseOrderDto> purchaseOrderList=new ArrayList<>();
		if(null != ids && !ids.isEmpty()){
			queryCondition.setIds(ids);
			purchaseOrderList=purchaseOrderDao.getPageList(queryCondition);
			Integer totalCount=this.getTotalCount(queryCondition);
			resultPager.setTotalServerItems(totalCount);
		}else{
			resultPager.setTotalServerItems(0);
		}
		resultPager.setData(purchaseOrderList);
		return resultPager;
	}

	/**
	 * 获取分页主键ID集合
	 */
	@Override
	public List<Integer> getPageIdList(QueryOrderConditionDto queryCondition) {
		return purchaseOrderDao.getPageIdList(queryCondition);
	}

	/**
	 * 获取总记录数
	 */
	@Override
	public Integer getTotalCount(QueryOrderConditionDto queryCondition) {
		return purchaseOrderDao.getTotalCount(queryCondition);
	}

	/**
	 * 获取未完成的发货单
	 * @return
     */
	@Override
	public List<OrderGoodsDto> getGoodsList(Long userId) {
		return purchaseOrderGoodsDao.getGoodsList(userId);
	}

	/**
	 * 通过主键获取对象
	 */
	@Override
	public PurchaseOrderDto selectByPrimaryKey(Integer id) {
		QueryOrderConditionDto queryCondition=new QueryOrderConditionDto();
		List<Integer> ids=new ArrayList<Integer>();
		ids.add(id);
		queryCondition.setIds(ids);
		List<PurchaseOrderDto> purchaseOrderList=purchaseOrderDao.getPageList(queryCondition);
		if(null!=purchaseOrderList&&0!=purchaseOrderList.size()){
			return purchaseOrderList.get(0);
		}
		return null;
	}
}
